package algorithm.middle;


import pojo.TreeNode;

import java.awt.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @author 江岸
 * @version V1.0
 * @ClassName: LevelOrder32
 * @description: 从上到下打印出二叉树的每个节点，同一层的节点按照从左到右的顺序打印。
 *
 *
 *
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 *
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 *
 * 返回：
 *
 * [3,9,20,15,7]
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 * @date 2021/3/1910:26
 * @since V1.0
 */
public class LevelOrder32 {

    //二叉树 队列
    public int[] levelOrder(TreeNode root) {
        if (root==null){
            return new int[0];
        }
        Queue<TreeNode> que = new LinkedList<TreeNode>();
        ArrayList<TreeNode> list = new ArrayList<TreeNode>();
        que.add(root);
        while (!que.isEmpty()){
            TreeNode poll = que.poll();
            list.add(poll);
            if (poll.left!=null) que.add(poll.left);
            if (poll.right!=null) que.add(poll.right);
        }
        int[] arr =  new int[list.size()];
        for (int i=0;i<list.size();i++) {
            arr[i] = list.get(i).val;
        }
        return arr;
    }


    AtomicInteger num =  new AtomicInteger(100);
    public static void main(String[] args) {
        LevelOrder32 levelOrder32 = new LevelOrder32();
        for (int i=0;i<5;i++){
            Thread thread = new Thread(()->{
                levelOrder32.fun();
            });
            thread.start();
        }

    }

    public void fun(){
        while (true){
            synchronized (this){
                if (num.get()>0){
                    try {
                        Thread.sleep(10);
                        System.out.println(Thread.currentThread().getName()+"***********"+num.getAndDecrement());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }else {
                    break;
                }
            }

        }
    }
}
